const first = document.querySelector('#number1');
const second = document.querySelector('#number2');
const fileUplaod = document.querySelector('#file-upload');

const result = document.querySelector('.result');
const CHUNKS_SIZE = 1 * 1024 * 1024;

if (window.Worker) {
  const myWorker = new Worker('./js/webworker.js', { name: 1 });

  // 文件分片
  const filefragment = (file, size = CHUNKS_SIZE) => {
    let curr = 0;
    const chunks = [];
    while (curr < file.size) {
      chunks.push({ index: curr, file: file.slice(curr, curr + size) });
      curr += size;
    }
    return chunks;
  };

  // 计算hash
  const calcHash = (chunks) => {
    return new Promise((resolve, reject) => {
      myWorker.postMessage({ chunks });
      myWorker.onmessage = (e) => {
        const { hash } = e.data;
        if (hash) {
          resolve(hash);
        } else {
          reject();
        }
      };
    });
  };

  first.onchange = function () {
    myWorker.postMessage([first.value, second.value]);
    console.log('数字1发生了变化');
  };

  second.onchange = function () {
    myWorker.postMessage([first.value, second.value]);
    console.log('数字2发生了变化');
  };

  fileUplaod.onchange = async function (e) {
    const file = e.target.files[0];
    if (!file) return;
    const chunks = filefragment(file);
    const hash = await calcHash(chunks);
    console.log(hash);
  };

  myWorker.onmessage = function (e) {
    result.textContent = e.data;
    console.log('接收返回结果');
  };
} else {
  console.log('您的浏览器不支持webworker');
}
